package cn.edu.gzmtu.dao;

import cn.edu.gzmtu.domain.Role;
import cn.edu.gzmtu.domain.UserInfo;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface IUserDao {

    @Select("select * from users where username=#{userName}")
    @Results({
            @Result(id=true, column = "id", property = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "cn.edu.gzmtu.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findByUsername(String userName) throws Exception;

    /**
     * 查询所有用户
     * @return
     */
    @Select("select * from users")
    List<UserInfo> findAll() throws Exception;

    /**
     * 添加用户
     * @param userInfo
     * @throws Exception
     */
    @Insert("insert into users(email, username, password, phonenum, status) values(#{email}, #{username}, #{password}, #{phoneNum}, #{status})")
    void save(UserInfo userInfo) throws Exception;

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    @Select("select * from users where id=#{id}")
    @Results({
            @Result(id = true, property = "id", column = "id"),
            @Result(property = "username", column = "username"),
            @Result(property = "email", column = "email"),
            @Result(property = "password", column = "password"),
            @Result(property = "phoneNum", column = "phoneNum"),
            @Result(property = "status", column = "status"),
            @Result(property = "roles", column = "id", javaType = java.util.List.class, many = @Many(select = "cn.edu.gzmtu.dao.IRoleDao.findRoleByUserId"))
    })
    UserInfo findById(String id);

    /**
     * 查询用户没有的角色
     * @param userId
     * @return
     */
    @Select("select * from role where id not in(select roleId from users_role where userId=#{userId})")
    List<Role> findUserOtherRoles(String userId) throws Exception;

    /**
     * 为用户添加角色
     * @param roleId
     */
    @Select("insert into users_role(userId, roleId) values(#{userId}, #{roleId})")
    void addRoleToUser(@Param("userId") String userId, @Param("roleId") String roleId);
}
